package com.wangy.sct.gateway.filter;

import com.wangy.sct.common.core.InvokeResult;
import com.wangy.sct.common.core.SctConstants;
import com.wangy.sct.common.core.SctEnum;
import com.wangy.sct.common.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * ClassName: AuthCheckFilter <br/>
 * Description: 全局Auth认证检查Filter，检查请求URL的token是否合法 <br/>
 *
 * @author wangyue
 * @version V1.0.0
 * @date 2018/11/19 2:33 PM
 */
@Configuration
public class AuthCheckFilter implements GlobalFilter, Ordered {

	@Value("${skip-serviceauth-check.url}")
	private String skipAuthCheckUrlOp;

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		long startTime = System.currentTimeMillis();
		ServerHttpRequest request = exchange.getRequest();
		String reqUrl = request.getURI().getPath();
		System.out.println("reqUrl:" + reqUrl);
		System.out.println("skipAuthCheckUrlOp:" + skipAuthCheckUrlOp);
		boolean authPass = false;
		if (StringUtils.isNotBlank(skipAuthCheckUrlOp)) {
			List<String> skipUrlList = Arrays.asList(skipAuthCheckUrlOp.split(SctConstants.SPLIT_COMMA));
			if (skipUrlList.stream().anyMatch((list) -> reqUrl.startsWith(list))) {
				authPass = true;
			} else {
				String authToken = request.getHeaders().get(SctConstants.HEADER_TOKEN_NAME).get(0);
				if (StringUtils.isNotBlank(authToken)) {
					try {
						JwtUtil.verify(authToken);
						authPass = true;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		if (authPass) {
			System.out.println("程序运行时间：" + (System.currentTimeMillis() - startTime) + "ms");
			return chain.filter(exchange);
		} else {
			InvokeResult invokeResult = new InvokeResult();
			invokeResult.setStatus(SctEnum.AUTH_FAILED_VERIFY_TOKEN);
			ServerHttpResponse response = exchange.getResponse();
			DataBuffer dataBuffer = response.bufferFactory().wrap(invokeResult.toString().getBytes());
			System.out.println("程序运行时间：" + (System.currentTimeMillis() - startTime) + "ms");
			return response.writeWith(Mono.just(dataBuffer));
		}
	}

	@Override
	public int getOrder() {
		return - 3;
	}

}
